<?php

/**
 * Created by PhpStorm.
 * User: CCA
 * Date: 2019/10/16
 * Time: 14:06
 */

namespace app\api\controller;


use app\api\BaseController;
use app\common\model\Refundreturn;
use think\Lang;


/**
 * @title 用户订单
 */
class Userorder extends BaseController
{

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'home/lang/' . config('default_lang') . '/memberorder.lang.php');
    }


    /**
     * @title 订单列表
     * @description
     * @author fuzz
     * @url /Userorder/select
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_sn 订单编号(搜索)
     * @param string query_start_date 开始时间(搜索)
     * @param string query_end_date 结束时间(搜索)
     * @param string state_type 订单状态
     * @return {"code":200,"msg":"succeess"}
     */
    public function select()
    {
        $order_status = input('order_status', '-1');   //-1:全部 '0：待付款 1：待收货 2：已完成 3：已取消';

        $page = intval(input('page')) ? intval(input('page')) : 1;
        $pagesize = intval(input('pagesize')) ? intval(input('pagesize')) : 15;
        $offset = ($page - 1) * $pagesize;

        if ($order_status == '-1') {
            $parms_status = [
                'order_status' => ['neq', 0],
                'is_cancel' => 0,
                'user_id' => $this->user_id
            ];
            $app_order_list = db('app_order')
                ->where($parms_status)
                ->order('create_time', 'desc')
                ->limit($offset, $pagesize)
                ->select();
        } else {
            switch ($order_status) {
                case 2:
                    #已完成包括 已完成
                    $where['is_cancel'] = 0;
                    $where['user_id'] = $this->user_id;
                    $where['order_status'] = array('eq', '2');
                    $app_order_list = db('app_order')->where($where)->order('create_time', 'desc')->limit($offset, $pagesize)->select();
                    break;
                case 3:
                    #已取消包括已退款
                    $where['is_cancel'] = 0;
                    $where['user_id'] = $this->user_id;
                    $where['order_status'] = array('in', '3,4');
                    $app_order_list = db('app_order')->where($where)->order('create_time', 'desc')->limit($offset, $pagesize)->select();
                    break;
                default:
                    $app_order_list = db('app_order')->where('is_cancel', 0)->where('user_id', $this->user_id)->where('order_status', $order_status)->order('create_time', 'desc')->limit($offset, $pagesize)->select();
                    break;
            }
        }
        if (empty($app_order_list)) {
            $app_order_list = array();
            json_success_return($app_order_list);
        }

        $config = db('config')->where('code', 'qiniu_http')->find();
        foreach ($app_order_list as  $k => $v) {

            $app_order_list[$k]['goods_list'] = db('ordergoods')->where('rec_id', 'in', $v['ordergoods_ids'])->select();

            #判断是否项目定制
            foreach ($app_order_list[$k]['goods_list'] as $key => $value) {
                if ($v['app_order_type'] == 2) {
                    $app_order_list[$k]['goods_list'][$key]['goods_pay_price'] = 0;
                    $app_order_list[$k]['goods_list'][$key]['goods_price'] = 0;
                }
            }

            $app_order_list[$k]['order_list'] = db('order')->where('order_id', 'in', $v['order_ids'])->select();
        }

        foreach ($app_order_list as  $k => $v) {

            foreach ($v['goods_list'] as  $ke => $va) {
                $goods_info = db('goods')->alias('g')
                    ->join('brand b', 'b.brand_id = g.brand_id')
                    ->where(['goods_id' => $va['goods_id']])
                    ->find();
                $app_order_list[$k]['goods_list'][$ke]['goods_name'] = $goods_info['brand_name'] . '  ' . $va['goods_name'];
                $app_order_list[$k]['goods_list'][$ke]['goods_image_url'] = $config['value'] . '/' . $va['goods_image'];
            }
        }
        json_success_return($app_order_list);
    }

    /**
     * @title 订单详情
     * @description
     * @author fuzz
     * @url /Userorder/detail
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @return {"code":200,"msg":"succeess"}
     */
    public function detail()
    {
        $apporder_id = intval(input('param.apporder_id'));
        if ($apporder_id <= 0) {
            return json_fail_return(lang('member_order_none_exist'));
        }

        $app_order_list = db('app_order')->where('user_id', $this->user_id)->where('app_order_id', $apporder_id)->find();
        $app_order_list['count_price'] = $app_order_list['goods_prices'] + $app_order_list['freight'];

        if ($app_order_list['app_order_type'] == 2) {
            $app_order_list['use_integral'] = 0;
        }
        // p($app_order_list);die;
        if (empty($app_order_list)) {
            json_fail_return('订单id信息错误');
        }
        $app_order_list['order_list'] = db('order')->where('order_id', 'in', $app_order_list['order_ids'])->select();

        foreach ($app_order_list['order_list'] as  $k => $v) {
            $app_order_list['order_list'][$k]['goods_list'] = db('ordergoods')->where('order_id', $v['order_id'])->select();

            #如果是项目定制的话 订单价格为0
            foreach ($app_order_list['order_list'][$k]['goods_list'] as $key => $value) {
                if ($app_order_list['app_order_type'] == 2) {
                    $app_order_list['order_list'][$k]['goods_list'][$key]['goods_pay_price'] = 0;
                    $app_order_list['order_list'][$k]['goods_list'][$key]['goods_price'] = 0;
                }
            }
        }

        $config = db('config')->where('code', 'qiniu_http')->find();
        // p($app_order_list);die;
        foreach ($app_order_list['order_list'] as  $k => $v) {
            $count = 0;
            foreach ($v['goods_list'] as  $ke => $va) {
                $new = [];
                $goods_info = db('goods')->alias('g')
                    ->join('goodscommon gc', 'gc.goods_commonid = g.goods_commonid')
                    ->join('brand b', 'b.brand_id = g.brand_id')
                    ->where(['goods_id' => $va['goods_id']])
                    ->find();
                  
                $new = [
                    'goods_name' => $goods_info['brand_name'] . '  ' . $va['goods_name'],
                    'goods_image_url' => $config['value'] . '/' . $va['goods_image'],
                    'b_name' => $goods_info['brand_name'],
                    'goods_class' => $va['gc_id'],
                    'type_model' => $va['spec_values'],
                    'new_goods_name' => $goods_info['goods_name'],
                ];
                #判断运营商是否下架商品
                $yys_id = get_parent_store_id();
                $y_goods_info = db('y_goods')->where(['store_id' => $yys_id, 'goods_id' => $va['goods_id']])->find();
                if (!$y_goods_info) {
                    $new['goods_status'] = 0; #0--下架
                }

                #判断当前商品是否参加折扣
                $discount_info = getDiscounInfoByGoodId($va['goods_id']);
                $new['discount_id'] = 0;
                if ($discount_info) {
                    $new['discount_id'] = $discount_info['xianshi_id'];
                }

                #是否上门安装
                $new['is_install'] = 0;
                if ($goods_info['install_money'] > 0) {
                    $new['is_install'] = 1;
                }

                $app_order_list['order_list'][$k]['goods_list'][$ke] = array_merge($app_order_list['order_list'][$k]['goods_list'][$ke], $new);

                $goods_info = db('goods')->where('goods_id', $va['goods_id'])->find();
                $count += $goods_info['score'];
                $new = [
                    'return_goods' => $goods_info['return_goods'],
                    'change_goods' => $goods_info['change_goods'],
                    'course_id' => $goods_info['course_id'],
                    'return_integral' => $goods_info['score'],
                    'count_integral' => $count,
                    'warranty_period' => $goods_info['warranty_period'],
                ];
              
                if($va['is_goods_door'] == 1){
                    $new['spec_values'] = '含有安装费' . (empty($goods_info['spec_values']) ? '' : ',') . $goods_info['spec_values'];
                }  
                $app_order_list['order_list'][$k]['goods_list'][$ke] = array_merge($app_order_list['order_list'][$k]['goods_list'][$ke], $new);
                //下单返回的积分
                $app_order_list['return_jifen'] = $count;
                if ($app_order_list['app_order_type'] == 2) {
                    $app_order_list['return_jifen'] = 0;
                }
            }
        }
        //判断是否企业认证
        $member_info = db('member')->where(['member_id' => $this->user_id])->find();
        if ($member_info['enterprise_status'] == 2) {
            $app_order_list['enterprise_status'] = 1;
        } else {
            $app_order_list['enterprise_status'] = 0;
        }
        json_success_return($app_order_list);
    }



    /**
     * @title 申请退换货接口
     * @description
     * @author fuzz
     * @url /Userorder/return_apply
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type    2：退货 3：换货
     * @return {"code":200,"msg":"succeess"}
     */
    public function return_apply()
    {
        $order_id = intval(input('param.order_id'));
        $apply_type = input('param.apply_type');
        $apply_reason = input('param.apply_reason');
        $apply_explain = input('param.apply_explain');
        $express_id = input('param.express_id');
        $invoice_no = input('param.invoice_no');
        $goods_id = input('param.goods_id');
        $rec_id = input('param.rec_id');
        //图片
        $apply_images = input('post.apply_images/a');

        if (empty($apply_type) || empty($order_id)) {
            return json_fail_return('参数错误');
        }

        if (empty($apply_explain)) {
            return json_fail_return('请填写您的说明理由');
        }

        //判断当前订单是否可以操作退换货
        $status = db('order')->where(['order_id' => $order_id])->find();

        if ($status['order_state'] >= 40 || $status['order_state'] <= 10) {
            return json_fail_return('无权操作');
        }

        //判断当前订单的商品是否包含退换货
        $order_model = new \app\common\model\Order();
        $condition = array();
        $condition['o.order_id'] = $order_id;
        $condition['o.buyer_id'] = $this->user_id;
        $order_info = $order_model->getReturnOrderInfo($condition);

        $goods_model = new \app\common\model\Goods();
        $return_info = $goods_model->getReturnInfo($order_info['goods_id']);
        //退换货
        if ($apply_type == 2) {
            //判断是否包含退货
            if ($return_info['return_goods'] == 0) {
                return json_fail_return('当前订单不支持退货');
            }
        } else {
            //判断是否包含退货
            if ($return_info['change_goods'] == 0) {
                return json_fail_return('当前订单不支持换货');
            }
        }

        //入库
        $result = $order_model->addReturnOrder($order_id, $apply_type, $apply_reason, $apply_explain, $this->user_id, $order_info, $express_id, $invoice_no, $goods_id, $rec_id, $apply_images);
        json_success_return();
    }

    /**
     * @title 退换货提交物流单号接口
     * @description
     * @author fuzz
     * @url /Userorder/add_logistics
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type   
     * @return {"code":200,"msg":"succeess"}
     */
    public function add_logistics()
    {
        $rec_id = intval(input('param.rec_id'));
        $order_id = intval(input('param.order_id'));
        $goods_id = intval(input('param.goods_id'));
        $express_name = input('param.express_name');
        $invoice_no = input('param.invoice_no');
        $type = input('param.type');

        if (empty($type)) {
            return json_fail_return('参数错误');
        }

        $update['express_name'] = $express_name;
        $update['invoice_no'] = $invoice_no;
        $return_info = db('refundreturn')->where(['order_id' => $order_id, 'goods_id' => $goods_id, 'buyer_id' => $this->user_id, 'refund_type' => $type])->update($update);
        db('ordergoods')->where(['rec_id' => $rec_id])->update(['is_logistics' => 1]);
        if (!empty($return_info)) {
            json_success_return();
        } else {
            json_fail_return();
        }
    }

    /**
     * @title 大订单退款接口
     * @description
     * @author fuzz
     * @url /Userorder/big_refund
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type   
     * @return {"code":200,"msg":"succeess"}
     */
    public function big_refund()
    {
        $app_order_id = intval(input('param.app_order_id'));
        $apply_type = input('param.apply_type');
        $apply_reason = input('param.apply_reason');
        $apply_explain = input('param.apply_explain');

        //图片
        $apply_images = input('post.apply_images/a');

        //将图片转为json存起来
        $pic_info = json_encode($apply_images);


        if (empty($apply_type) || empty($app_order_id)) {
            return json_fail_return('参数错误');
        }
        if (empty($apply_explain)) {
            return json_fail_return('请填写退款说明');
        }

        $app_order_info = db('app_order')->where(['app_order_id' => $app_order_id])->find();

        //判断子订单有没有已发货的
        $order_ids = explode(',', $app_order_info['order_ids']);
        foreach ($order_ids as $k => $v) {
            $order_info = db('order')->where(['order_id' => $v])->find();
            if ($order_info['order_state'] > 20) {
                //发货以后就不能退款了
                return json_fail_return('当前订单已发货,无法退款');
            }
        }

        if ($app_order_info['order_status'] <= 0 || $app_order_info['order_status'] >= 2) {
            return json_fail_return('无权操作');
        }

        $order_model = new \app\common\model\Order();
        //入库
        $result = $order_model->addBigRefundOrder($app_order_id, $apply_type, $apply_reason, $apply_explain, $this->user_id, $app_order_info, $pic_info);
        if (!empty($result)) {
            json_success_return();
        } else {
            json_fail_return();
        }
    }

    /**
     * @title 大订单取消退款接口
     * @description
     * @author fuzz
     * @url /Userorder/big_refund
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type   
     * @return {"code":200,"msg":"succeess"}
     */
    public function cancel_refund()
    {
        $app_order_id = intval(input('param.app_order_id'));

        if (empty($app_order_id)) {
            return json_fail_return('参数错误');
        }

        $app_order_info = db('app_order')->where(['app_order_id' => $app_order_id])->find();

        $order_ids = explode(',', $app_order_info['order_ids']);

        db('refundreturn')->where(['app_order_id' => $app_order_id])->delete();
        foreach ($order_ids as $key => $value) {
            $result = db('order')->where(['order_id' => $value])->update(['refund_state' => 0]);
        }
        //大订单取消退款
        db('app_order')->where(['app_order_id' => $app_order_id])->update(['refund_price' => 0]);

        json_success_return();
    }

    /**
     * @title 获取企业类型接口
     * @description
     * @author fuzz
     * @url /Userorder/get_enterprise_type
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type   
     * @return {"code":200,"msg":"succeess"}
     */
    public function get_enterprise_type()
    {
        $result = db('enterprisetype')->where(['status' => 1, 'enterprisetype_del' => 0])->select();
        json_success_return($result);
    }

    /**
     * @title 申请企业认证接口
     * @description
     * @author fuzz
     * @url /Userorder/get_enterprise
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type   
     * @return {"code":200,"msg":"succeess"}
     */
    public function get_enterprise()
    {
        $data = input('post.');

        //将图片转为json存起来
        $enterprise_license = input('post.enterprise_license/a', '');
        if (!$enterprise_license) {
            return json_fail_return('请上传企业营业执照');
        }
        $pic_info = json_encode($enterprise_license);
        //验证格式
        if (empty($data['enterprise_name'])) {
            return json_fail_return('企业名称不能为空');
        }
        if (empty($data['contact_title'])) {
            return json_fail_return('联系人职位不能为空');
        }
        //联系人职位
        if (is_numeric($data['contact_title'])) {
            return json_fail_return('联系人职位格式错误');
        }
        if (empty($data['contact_name'])) {
            return json_fail_return('联系人姓名不能为空');
        }
        //联系人
        if (is_numeric($data['contact_name'])) {
            return json_fail_return('联系人姓名格式错误');
        }
        if (empty($data['contact_phone'])) {
            return json_fail_return('联系方式不能为空');
        }
        if (is_mobile($data['contact_phone']) == false) {
            return json_fail_return('联系方式格式不正确');
        }
        if (empty($data['contact_address'])) {
            return json_fail_return('联系人地址不能为空');
        }

        //获取企业类型信息
        $enterprise_type_info = db('enterprisetype')->where(['id' => $data['enterprise_type']])->find();

        $enterprise_update['enterprise_name'] = $data['enterprise_name'];
        $enterprise_update['enterprise_type'] = $enterprise_type_info['id'];
        $enterprise_update['enterprise_type_name'] = $enterprise_type_info['name'];
        // 营业执照
        $enterprise_update['enterprise_license'] = $pic_info;
        $enterprise_update['contact_title'] = $data['contact_title'];
        $enterprise_update['contact_name'] = $data['contact_name'];
        $enterprise_update['contact_phone'] = $data['contact_phone'];
        $enterprise_update['contact_landline'] = $data['contact_landline'];
        $enterprise_update['contact_address'] = $data['contact_address'];
        $enterprise_update['enterprise_status'] = 1;
        $enterprise_update['enterprise_time'] = time();

        //更新member表
        db('member')->where(['member_id' => $this->user_id])->update($enterprise_update);
        json_success_return();
    }

    /**
     * @title 返回企业认证状态
     * @description
     * @author fuzz
     * @url /Userorder/get_enterprise
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string examine_type     1-- 查是否可以显示发票按钮  2--查企业认证审核状态
     * @return {"code":200,"msg":"succeess"}
     */
    public function get_enterprise_status()
    {
        $info = db('member')->where(['member_id' => $this->user_id])->find();

        if (!empty($info['enterprise_license'])) {
            $info['enterprise_license'] = json_decode($info['enterprise_license'], true);
        } else {
            $info['enterprise_license'] = [];
        }

        if (empty($info['enterprise_name'])) {
            $status['type'] = '0';
            $status['msg'] = '0';
            json_success_return($status);
        }
        switch ($info['enterprise_status']) {
            case 0:
                $status['type'] = '0';
                $status['msg'] = '';
                $status['data'] = $info;
                break;
            case 1:
                $status['type'] = '1';
                $status['msg'] = '待审核';
                $status['data'] = $info;
                break;
            case 2:
                $status['type'] = '2';
                $status['msg'] = '审核通过';
                $status['data'] = $info;
                break;
            case 3:
                $status['type'] = '3';
                $status['msg'] = $info['reasons'];
                $status['data'] = $info;
                break;
            default:
                break;
        }
        json_success_return($status);
    }

    /**
     * @title 获取发票类型接口
     * @description
     * @author fuzz
     * @url /Userorder/get_invoice_type
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type   
     * @return {"code":200,"msg":"succeess"}
     */
    public function get_invoice_type()
    {
        $result = db('invoice_type')->where(['status' => 1, 'is_del' => 0])->select();
        json_success_return($result);
    }


    /**
     * @title 商城、项目定制  申请发票接口
     * @description
     * @author fuzz
     * @url /Userorder/application_invoice
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type   
     * @return {"code":200,"msg":"succeess"}
     
     */
    public function application_invoice()
    {
        $data = input('post.');

        //判断开户银行
        if (!empty($data['invoice_reg_bname'])) {
            if (is_numeric($data['invoice_reg_bname'])) {
                return json_fail_return('开户银行格式错误');
            }
        }
        //判断开户账号
        /*if(empty($data['invoice_reg_baccount'])){
            return json_fail_return('银行账号不能为空');
        }*/
        // if (!empty($data['invoice_reg_baccount'])) {
        //     if (!is_numeric($data['invoice_reg_baccount']) || strlen($data['invoice_reg_baccount']) != 19) {
        //         return json_fail_return('开户账号格式错误');
        //     }
        // }
        //判断电子邮箱
        if (!empty($data['invoice_email'])) {
            if (is_email($data['invoice_email']) == false) {
                return json_fail_return('邮箱格式错误');
            }
        }

        //判断单位名称
        if (isset($data['invoice_company']) && $data['invoice_company'] == "") {
            return json_fail_return('单位名称不能为空');
        }

        //判断统一社会信用代码
        if (isset($data['invoice_company_code']) && $data['invoice_company_code'] == "") {
            return json_fail_return('单位税号不能为空');
        }
        if (isset($data['invoice_company_code'])) {
            $test = "/^[_0-9A-Z]{18}$/i";
            if (!preg_match($test, $data['invoice_company_code'])) {
                return json_fail_return('统一社会信用代码格式错误');
            }
        }
        //判断注册地址
        if (isset($data['invoice_reg_addr']) && $data['invoice_reg_addr'] == "") {
            return json_fail_return('注册地址不能为空');
        }
        //判断注册电话
        if (isset($data['invoice_reg_phone']) && $data['invoice_reg_phone'] == "") {
            return json_fail_return('注册电话不能为空');
        }

        //判断是否企业认证过
        $enterprise_info = db('member')->where(['member_id' => $this->user_id])->find();
        if ($enterprise_info['enterprise_status'] != 2) {
            return json_fail_return('当前无法操作');
        }

        //获取发票类型信息
        $invoice_type = db('invoice_type')->where(['id' => $data['invoice_state_id']])->find();

        //获取地址信息
        if (!empty($data['invoice_goto_addr_id'])) {
            $address_info = db('address')->where(['member_id' => $this->user_id, 'address_id' => $data['invoice_goto_addr_id']])->find();
        }


        //发票内容
        $invoice_insert['invoice_content'] = $data['invoice_content'];

        //如果是个人，纸质发票的话  
        if ($data['invoice_head'] == 0 && $data['invoice_texture'] == 0) {
            //收货人 收货人电话 收货人地址
            $invoice_insert['invoice_rec_name'] = $address_info['address_realname'];
            $invoice_insert['invoice_rec_mobphone'] = $address_info['address_tel_phone'];
            $invoice_insert['invoice_goto_addr'] = $address_info['area_info'] . $address_info['address_detail'];
            $invoice_insert['invoice_rec_province'] = $address_info['area_info'];
        }

        //如果是个人，电子发票的话
        if ($data['invoice_head'] == 0 && $data['invoice_texture'] == 1) {
            //邮箱  联系方式
            $invoice_insert['invoice_email'] = $data['invoice_email'];
            $invoice_insert['invoice_phone'] = $data['invoice_phone'];
        }

        //如果是单位，纸质发票的话
        if ($data['invoice_head'] == 1 && $data['invoice_texture'] == 0) {
            // 单位名称 单位税号 收货人 收货人电话 收货人地址 注册地址  注册电话  开户银行 银行账号
            $invoice_insert['invoice_company'] = $data['invoice_company'];
            $invoice_insert['invoice_company_code'] = $data['invoice_company_code'];
            $invoice_insert['invoice_rec_name'] = $address_info['address_realname'];
            $invoice_insert['invoice_rec_mobphone'] = $address_info['address_tel_phone'];
            $invoice_insert['invoice_goto_addr'] = $address_info['area_info'] . $address_info['address_detail'];
            $invoice_insert['invoice_rec_province'] = $address_info['area_info'];
            $invoice_insert['invoice_reg_addr'] = $data['invoice_reg_addr'];
            $invoice_insert['invoice_reg_phone'] = $data['invoice_reg_phone'];
            $invoice_insert['invoice_reg_bname'] = $data['invoice_reg_bname'];
            $invoice_insert['invoice_reg_baccount'] = $data['invoice_reg_baccount'];
        }

        //如果是单位,电子发票的话
        if ($data['invoice_head'] == 1 && $data['invoice_texture'] == 1) {
            //单位名称 单位税号 邮箱 联系方式
            $invoice_insert['invoice_company'] = $data['invoice_company'];
            $invoice_insert['invoice_company_code'] = $data['invoice_company_code'];
            $invoice_insert['invoice_email'] = $data['invoice_email'];
            $invoice_insert['invoice_phone'] = $data['invoice_phone'];
        }

        //基本信息
        $invoice_insert['member_id'] = $this->user_id;
        $invoice_insert['app_order_id'] = $data['app_order_id'];

        //发票类型
        $invoice_insert['invoice_type_id'] = $invoice_type['id'];
        $invoice_insert['c_time'] = time();

        //发票类型 （invoice_texture 0--纸质 1--电子）
        $invoice_insert['invoice_texture'] = $data['invoice_texture'];
        //发票抬头  （invoice_head 0--个人 1--单位）
        $invoice_insert['invoice_head'] = $data['invoice_head'];

        # 1--商城发票 2--项目定制发票 3--服务单发票
        $invoice_insert['invoice_type'] = $data['invoice_type'];

        #判断服务单发票，还是商城、项目定制发票
        switch ($data['invoice_type']) {
            case 3:
                $invoice_examine_status = db('s_order')->where(['order_id' => $data['app_order_id']])->find();

                if($invoice_examine_status['service_invoice_status'] == 1){
                    return json_fail_return('已提交发票申请，请勿重复提交');
                }
                if ($invoice_examine_status['service_invoice_status'] == 2) {
                    db('invoice')->where(['app_order_id' => $data['app_order_id']])->update($invoice_insert);
                } else {
                    db('invoice')->insertGetId($invoice_insert);
                }

                db('s_order')->where(['order_id' => $data['app_order_id']])->update(['service_invoice_status' => 1]);

                break;
            default:
                //判断是添加还是修改
                //获取发票的审核状态
                $invoice_examine_status = db('app_order')->where(['app_order_id' => $data['app_order_id']])->find();

                //如果是审核未通过
                if ($invoice_examine_status['invoice_status'] == 2) {
                    db('invoice')->where(['app_order_id' => $data['app_order_id']])->update($invoice_insert);
                } else {
                    db('invoice')->insertGetId($invoice_insert);
                }
                //修改大订单发票状态
                db('app_order')->where(['app_order_id' => $data['app_order_id']])->update(['invoice_status' => 1]);
                break;
        }
        json_success_return();
    }
    /**
     * @title 获取发票的默认地址
     * @description
     * @author fuzz
     * @url /Userorder/get_invoice_address
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string examine_type     1-- 查是否可以显示发票按钮  2--查企业认证审核状态
     * @return {"code":200,"msg":"succeess"}
     */
    public function get_invoice_address()
    {


        $address_info = model('address')->getDefaultAddressInfo(array('member_id' => $this->user_id));

        json_success_return($address_info);
    }

    /**
     * @title 返回发票状态
     * @description
     * @author fuzz
     * @url /Userorder/get_invoice_status
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string examine_type     1-- 查是否可以显示发票按钮  2--查企业认证审核状态
     * @return {"code":200,"msg":"succeess"}
     */
    public function get_invoice_status()
    {
        $data = input('post.');
        $app_order_id = intval(input('param.app_order_id'));

        if (empty($app_order_id)) {
            return json_fail_return('参数错误');
        }

        if ($data['invoice_type'] == 3) {
            #服务单
            $info = db('s_order')->where(['order_id' => $app_order_id])->find();
            if ($info['service_invoice_status'] == 0) {
                $status['type'] = '0';
                $status['msg'] = '未申请';
                json_success_return($status);
            }
            if ($info['service_invoice_status'] != 0) {
                $invoice_info = db('invoice')->where(['app_order_id' => $app_order_id])->find();
                $status['invoice_info'] = $invoice_info;
                $status['invoice_info']['app_order_sn'] = $info['order_sn'];
            }
            switch ($info['service_invoice_status']) {
                case 1:
                    $status['type'] = '1';
                    $status['msg'] = '待审核';
                    break;
                case 2:
                    $status['type'] = '2';
                    $status['msg'] = $info['service_invoice_reasons'];
                    break;
                case 3:
                    $status['type'] = '3';
                    $status['msg'] = '';
                    break;
                default:
                    break;
            }
        } else {
            #商城，项目定制
            $info = db('app_order')->where(['app_order_id' => $app_order_id])->find();

            if ($info['invoice_status'] == 0) {
                $info['type'] = '0';
                $info['msg'] = '未申请';
                $info['app_order_sn'] = $info['order_sn'];
                json_success_return($info);
            }
            if ($info['invoice_status'] != 0) {
                $invoice_info = db('invoice')->where(['app_order_id' => $app_order_id])->find();
                $status['invoice_info'] = $invoice_info;
                $status['invoice_info']['app_order_sn'] = $info['order_sn'];
            }
            switch ($info['invoice_status']) {
                case 1:
                    $status['type'] = '1';
                    $status['msg'] = '待审核';
                    break;
                case 2:
                    $status['type'] = '2';
                    $status['msg'] = $info['invoice_no_content'];
                    break;
                case 3:
                    $status['type'] = '3';
                    $status['msg'] = $info['invoice_logistics'];
                    break;
                default:
                    break;
            }
        }
        json_success_return($status);
    }

    /**
     * @title 获取服务单拒单原因
     * @description
     * @param string goods_id 商品id null true
     * @return {"code":200,"msg":"succeess"}
     * *@author zjw
     * @url /goods/get_return_reason
     * @method GET
     *
     * @code 200 成功
     * @code 201 失败
     *
     */

    public function get_refusal_reason()
    {
        $RefundreturnModel = new Refundreturn();
        $type = intval(input('post.type'));
        if (empty($type)) {
            return json_fail_return('参数错误');
        }
        $result = $RefundreturnModel->getRefusalReason($type);
        return json_success_return($result);
    }

    /**
     * @title 取消退换货接口
     * @description
     * @author fuzz
     * @url /Userorder/cancel_apply
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string apply_type    1 退款   2 退换货
     * @return {"code":200,"msg":"succeess"}
     */
    public function cancel_apply()
    {
        $order_id = intval(input('param.order_id'));
        $apply_type = intval(input('param.apply_type'));
        $goods_id = intval(input('param.goods_id'));

        $rec_id = intval(input('param.rec_id'));
        if (empty($order_id) || empty($apply_type)) {
            return json_fail_return('参数错误');
        }

        db('refundreturn')->where(['order_id' => $order_id])->delete();
        if ($apply_type == 1) {
            //退款
            db('order')->where(['order_id' => $order_id])->update(['refund_state' => 0]);
            db('ordergoods')->where(['order_id' => $order_id])->update(['return_status' => 0]);
        } else {
            //退换货
            db('ordergoods')->where(['rec_id' => $rec_id])->update(['return_status' => 0]);
        }

        json_success_return();
    }


    /**
     * @title 改变订单状态
     * @description
     * @author fuzz
     * @url /Userorder/detail
     * @method POST
     *
     * @code 200 成功
     * @code 201 失败
     *
     * @param string order_id 订单id
     * @param string state_type 操作命令order_cancel取消订单order_receive收货order_recycle删除
     * @return {"code":200,"msg":"succeess"}
     */
    public function changeState()
    {
        $state_type = input('param.state_type');
        $order_id = intval(input('param.order_id'));
        $app_order_id = intval(input('param.app_order_id'));
        $cantion_reason = intval(input('param.cantion_reason'));
        $apply_explain = input('param.apply_explain');

        if (empty($state_type) || empty($order_id)) {
            return json_fail_return('参数错误');
        }

        //获取订单详情
        $order_model = new \app\common\model\Order();
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['buyer_id'] = $this->user_id;
        $order_info = $order_model->getOrderInfo($condition);

        //取消订单
        if ($state_type == 'order_cancel') {
            if (empty($apply_explain)) {
                return json_fail_return('请填写取消订单说明');
            }
            $result = $this->_order_cancel($order_info, input('post.'), $app_order_id, $cantion_reason, $apply_explain);
        } else if ($state_type == 'order_receive') {
            //   收货 
            $result = $this->_order_receive($order_info, input('post.'), $app_order_id);
        } else if (in_array($state_type, array('order_delete', 'order_drop', 'order_restore'))) {
            $result = $this->_order_recycle($order_info, input('post.'));
        } else {
            exit();
        }
        // if (!$result['code']) {
        //     json_success_return($result['msg']);
        // } else {

        //     json_fail_return($result['msg']);
        // }
        if (!$result['code']) {
            json_fail_return($result['msg']);
        } else {
            json_success_return($result['msg']);
        }
    }


    /**
     * 回收站
     */
    private function _order_recycle($order_info, $get)
    {
        $order_model = new \app\common\model\Order();
        $logic_order = new \app\common\logic\Order();
        $state_type = str_replace(array('order_delete', 'order_drop', 'order_restore'), array('delete', 'drop', 'restore'), input('param.state_type'));
        $if_allow = $order_model->getOrderOperateState($state_type, $order_info);
        if (!$if_allow) {
            return ds_callback(false, lang('have_right_operate'));
        }

        return $logic_order->changeOrderStateRecycle($order_info, 'buyer', $state_type);
    }

    /**
     * 取消订单
     */
    private function _order_cancel($order_info, $post, $app_order_id, $cantion_reason, $apply_explain)
    {
        $order_model = new \app\common\model\Order();
        $logic_order = new \app\common\logic\Order();
        $if_allow = $order_model->getOrderOperateState('buyer_cancel', $order_info);
        if (!$if_allow) {
            return ds_callback(false,  lang('have_right_operate'));
        }

        //$msg = $post['state_info1'] != '' ? $post['state_info1'] : $post['state_info'];
        // return $logic_order->changeOrderStateCancel($order_info, 'buyer', $this->user_id, $msg);
        return $logic_order->changeOrderStateCancel($order_info, 'buyer', $this->user_id, $app_order_id, $cantion_reason, $apply_explain);
    }

    /**
     * 收货
     */
    private function _order_receive($order_info, $post, $app_order_id)
    {
        $order_model = new \app\common\model\Order();
        $logic_order = new \app\common\logic\Order();
        $if_allow = $order_model->getOrderOperateState('receive', $order_info);
        if (!$if_allow) {
            return ds_callback(false,  lang('have_right_operate'));
        }

        return $logic_order->changeOrderStateReceive($order_info, 'buyer', $this->user_id, $app_order_id);
    }

    public function refund(Refundreturn $refundreturn_model)
    {
        $condition = array();
        $reason_list = $refundreturn_model->getReasonList($condition); //退款退货原因
        $this->assign('reason_list', $reason_list);
        $order_id = intval(input('param.order_id'));
        $goods_id = intval(input('param.goods_id')); //订单商品表编号
        if ($order_id < 1 || $goods_id < 1) { //参数验证
            return json_fail_return(lang('wrong_argument'));
        }
        $condition = array();
        $condition['buyer_id'] = $this->user_id;
        $condition['order_id'] = $order_id;

        $order = $refundreturn_model->getRightOrderList($condition, $goods_id);
        $order_id = $order['order_id'];
        $order_amount = $order['order_amount']; //订单金额
        $order_refund_amount = $order['refund_amount']; //订单退款金额
        $goods_list = $order['goods_list'];
        $goods = $goods_list[0];
        $goods_pay_price = $goods['goods_pay_price']; //商品实际成交价
        if ($order_amount < ($goods_pay_price + $order_refund_amount)) {
            $goods_pay_price = $order_amount - $order_refund_amount;
            $goods['goods_pay_price'] = $goods_pay_price;
        }
        $result = array(
            'goods' => $goods,
            'order' => $order,
            'store' => $order['extend_store'],
            'order_common' => $order['extend_order_common'],
            'goods_list' => $order['goods_list'],
        );


        $goods_id = $goods['rec_id'];
        $condition = array();
        $condition['buyer_id'] = $order['buyer_id'];
        $condition['order_id'] = $order['order_id'];
        $condition['order_goods_id'] = $goods_id;
        $condition['seller_state'] = array('lt', '3');
        $refund_list = $refundreturn_model->getRefundreturnList($condition);
        $refund = array();
        if (!empty($refund_list) && is_array($refund_list)) {
            $refund = $refund_list[0];
        }
        $refund_state = $refundreturn_model->getRefundState($order); //根据订单状态判断是否可以退款退货

        if ((isset($refund['refund_id']) && $refund['refund_id'] > 0) || $refund_state != 1) { //检查订单状态,防止页面刷新不及时造成数据错误
            return json_fail_return(lang('wrong_argument'));
        }
        if (request()->isPost() && $goods_id > 0) {
            $refund_array = array();
            $refund_amount = floatval(input('post.refund_amount')); //退款金额
            if (($refund_amount < 0) || ($refund_amount > $goods_pay_price)) {
                $refund_amount = $goods_pay_price;
            }
            $goods_num = intval(input('post.goods_num')); //退货数量
            if (($goods_num < 0) || ($goods_num > $goods['goods_num'])) {
                $goods_num = 1;
            }
            $refund_array['reason_info'] = '';
            $reason_id = intval(input('post.reason_id')); //退货退款原因
            $refund_array['reason_id'] = $reason_id;
            $reason_array = array();
            $reason_array['reason_info'] = lang('other');
            $reason_list[0] = $reason_array;
            if (!empty($reason_list[$reason_id])) {
                $reason_array = $reason_list[$reason_id];
                $refund_array['reason_info'] = $reason_array['reason_info'];
            }

            $pic_array = array();
            $pic_array['buyer'] = $this->upload_pic(); //上传凭证
            $info = serialize($pic_array);
            $refund_array['pic_info'] = $info;

            $trade_model = model('trade');
            $order_shipped = $trade_model->getOrderState('order_shipped'); //订单状态30:已发货
            if ($order['order_state'] == $order_shipped) {
                $refund_array['order_lock'] = '2'; //锁定类型:1为不用锁定,2为需要锁定
            } else {
                $refund_array['order_lock'] = '1';
            }

            $refund_array['refund_type'] = input('post.refund_type'); //类型:1为退款,2为退货
            $show_url = url('Memberreturn/index');
            $refund_array['return_type'] = '2'; //退货类型:1为不用退货,2为需要退货
            if ($refund_array['refund_type'] != '2') {
                $refund_array['refund_type'] = '1';
                $refund_array['return_type'] = '1';
                $show_url = url('Memberrefund/index');
            }
            $refund_array['seller_state'] = '1'; //状态:1为待审核,2为同意,3为不同意
            $refund_array['refund_amount'] = ds_price_format($refund_amount);
            $refund_array['goods_num'] = $goods_num;
            $refund_array['buyer_message'] = input('post.buyer_message');
            $refund_array['add_time'] = time();
            $state = $refundreturn_model->addRefundreturn($refund_array, $order, $goods);

            if ($state) {
                if ($order['order_state'] == $order_shipped) {
                    $refundreturn_model->editOrderLock($order_id);
                }
                return json_success_return([], '退款成功');
            } else {
                return json_fail_return('退款失败');
            }
        } else {
            $result['state_array'] = $this->getRefundStateArray();
            return json_success_return($result);
        }
    }

    function getRefundStateArray($type = 'all')
    {
        $state_array = array(
            '1' => lang('refund_state_confirm'),
            '2' => lang('refund_state_yes'),
            '3' => lang('refund_state_no')
        ); //卖家处理状态:1为待审核,2为同意,3为不同意

        $admin_array = array(
            '1' => lang('in_processing'),
            '2' => lang('to_be_processed'),
            '3' => lang('has_been_completed')
        ); //确认状态:1为买家或卖家处理中,2为待平台管理员处理,3为退款退货已完成

        $state_data = array(
            'seller' => $state_array,
            'admin' => $admin_array
        );
        if ($type == 'all') {
            return $state_data; //返回所有
        }
        return $state_data[$type];
    }
}
